<script setup>
import { computed, inject } from 'vue'
import { LeftOutlined, AimOutlined, RightOutlined, CaretRightOutlined, PauseOutlined } from '@ant-design/icons-vue';
import * as utils from 'video-action/libs/utils.js';
import ActionIndicator from 'video-action/annotation/components/action-indicator.vue';
import { xsToOpts } from '@/util/index.js';

const primaryMainElem = inject('primaryMainElem');
const addShortcutKey = inject('addShortcutKey');
const video = inject('video');
const annotationState = inject('annotationState');
const layers = inject('layers');

const isPaused = inject('isPaused');
const isStopped = inject('isStopped');
const showVideoPlayer = inject('showVideoPlayer');
const stop = inject('stop');
const handlePlayPause = inject('handlePlayPause');
const handleStop = inject('handleStop');

addShortcutKey(['p'], handlePlayPause);

const videoPlaybackRateOptions = xsToOpts([0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 5.0]);

// right buttons
const nearestKeyframe = (currentFrame) => {
  let min = video.value.frames
  let nearestKeyframe = currentFrame
  for (let i = 0; i < annotationState.value.keyframeList.length; i++) {
    let distance = Math.abs(currentFrame - annotationState.value.keyframeList[i])
    if (distance < min) {
      min = distance
      nearestKeyframe = annotationState.value.keyframeList[i]
    }
  }
  return nearestKeyframe
}
const handlePreviousKeyframe = () => {
  // base on right most one
  const leftCurrentKeyFrame = nearestKeyframe(annotationState.value.frame.left)
  const rightCurrentKeyFrame = nearestKeyframe(annotationState.value.frame.right)
  const leftCurrentKeyFrameIndex = annotationState.value.keyframeList.indexOf(leftCurrentKeyFrame)
  const rightCurrentKeyFrameIndex = annotationState.value.keyframeList.indexOf(rightCurrentKeyFrame)
  if (leftCurrentKeyFrameIndex <= 0 || rightCurrentKeyFrameIndex <= 0) {
    annotationState.value.frame.left = 0
    annotationState.value.frame.right = annotationState.value.keyframeList[1] || 0
  } else if (leftCurrentKeyFrameIndex === rightCurrentKeyFrameIndex) {
    annotationState.value.frame.left = annotationState.value.keyframeList[rightCurrentKeyFrameIndex - 1]
    annotationState.value.frame.right = rightCurrentKeyFrame
  } else if (leftCurrentKeyFrameIndex < rightCurrentKeyFrameIndex) {
    if (rightCurrentKeyFrameIndex - 2 < 0) {
      annotationState.value.frame.left = 0
      annotationState.value.frame.right = annotationState.value.keyframeList[1] || 0
    } else {
      annotationState.value.frame.left = annotationState.value.keyframeList[rightCurrentKeyFrameIndex - 2]
      annotationState.value.frame.right = annotationState.value.keyframeList[rightCurrentKeyFrameIndex - 1]
    }
  } else {
    annotationState.value.frame.left = rightCurrentKeyFrame
    annotationState.value.frame.right = leftCurrentKeyFrame
  }
}
const handleNearestKeyframe = () => {
  const leftCurrentKeyFrame = nearestKeyframe(annotationState.value.frame.left)
  const rightCurrentKeyFrame = nearestKeyframe(annotationState.value.frame.right)
  const leftCurrentKeyFrameIndex = annotationState.value.keyframeList.indexOf(leftCurrentKeyFrame)
  const rightCurrentKeyFrameIndex = annotationState.value.keyframeList.indexOf(rightCurrentKeyFrame)
  if (rightCurrentKeyFrameIndex - leftCurrentKeyFrameIndex === 1) {
    annotationState.value.frame.left = leftCurrentKeyFrame
    annotationState.value.frame.right = rightCurrentKeyFrame
  } else {
    annotationState.value.frame.left = leftCurrentKeyFrame
    annotationState.value.frame.right =
      annotationState.value.keyframeList[leftCurrentKeyFrameIndex + 1] || leftCurrentKeyFrame
  }
}
const handleNextKeyframe = () => {
  // base on left most one
  const leftCurrentKeyFrame = nearestKeyframe(annotationState.value.frame.left)
  const rightCurrentKeyFrame = nearestKeyframe(annotationState.value.frame.right)
  const leftCurrentKeyFrameIndex = annotationState.value.keyframeList.indexOf(leftCurrentKeyFrame)
  const rightCurrentKeyFrameIndex = annotationState.value.keyframeList.indexOf(rightCurrentKeyFrame)
  const lastIndex = annotationState.value.keyframeList.length - 1
  if (leftCurrentKeyFrameIndex >= lastIndex || rightCurrentKeyFrameIndex >= lastIndex) {
    annotationState.value.frame.left =
      lastIndex - 1 >= 0 ? annotationState.value.keyframeList[lastIndex - 1] : annotationState.value.keyframeList[lastIndex]
    annotationState.value.frame.right = annotationState.value.keyframeList[lastIndex]
  } else if (leftCurrentKeyFrameIndex === rightCurrentKeyFrameIndex) {
    annotationState.value.frame.left = leftCurrentKeyFrame
    annotationState.value.frame.right = annotationState.value.keyframeList[leftCurrentKeyFrameIndex + 1]
  } else if (leftCurrentKeyFrameIndex < rightCurrentKeyFrameIndex) {
    if (leftCurrentKeyFrameIndex + 2 > lastIndex) {
      annotationState.value.frame.left =
        lastIndex - 1 >= 0 ? annotationState.value.keyframeList[lastIndex - 1] : annotationState.value.keyframeList[lastIndex]
      annotationState.value.frame.right = annotationState.value.keyframeList[lastIndex]
    } else {
      annotationState.value.frame.left = annotationState.value.keyframeList[leftCurrentKeyFrameIndex + 1]
      annotationState.value.frame.right = annotationState.value.keyframeList[leftCurrentKeyFrameIndex + 2]
    }
  } else {
    annotationState.value.frame.left = leftCurrentKeyFrame
    annotationState.value.frame.right = annotationState.value.keyframeList[leftCurrentKeyFrameIndex + 1]
  }
}

// middle range
const currentFrameRange = computed({
  get: () => [
    annotationState.value.frame.left,
    annotationState.value.frame.right
  ],
  set: value => {
    showVideoPlayer.value && stop();
    Object.assign(annotationState.value.frame, R.zipObj(['left', 'right'], value));
  }
})

const tipFormatter = value => `${value} | ${utils.toFixed2(utils.index2time(video.value.fps, value))} s`;
</script>

<template>
  <div class="keyframe-panel">
    <div class="btn-group">
      <a-tooltip placement="topLeft">
        <template #title>{{ isPaused ? '播放 (p)' : '暂停 (p)' }}</template>
        <a-button
          shape="circle"
          @click="handlePlayPause"
          :disabled="!video.frames"
        >
        <template #icon>
          <template v-if="isPaused">
            <caret-right-outlined />
          </template>
          <template v-else>
            <pause-outlined />
          </template>
        </template>
        </a-button>
      </a-tooltip>
      <a-tooltip>
        <template v-if="showVideoPlayer" #title>停止</template>
        <a-button
          shape="circle"
          :disabled="!showVideoPlayer"
          @click="handleStop"
        >
          <span class="icon-stop"></span>
        </a-button>
      </a-tooltip>
    </div>
    <label>
      倍速
      <a-select
        :disabled="!isStopped"
        v-model:value="annotationState.videoPlaybackRate"
        :options="videoPlaybackRateOptions"
        style="width: 6em;"
      />
    </label>
    
    <div style="margin-top: -10px; flex: 1;">
      <a-slider
        v-model:value="currentFrameRange"
        range
        :min="0"
        :max="video.frames - 1"
        :step="1"
        :tip-formatter="tipFormatter"
        :disabled="!video.frames"
        :get-tooltip-popup-container="() => primaryMainElem.firstElementChild"
      >
      </a-slider>
      <action-indicator
        v-if="0 < layers.length"
        @jump="stop"
      />
    </div>
    
    <div class="btn-group">
      <a-tooltip>
        <template #title>上一个关键帧 (&lt)</template>
        <a-button
          @click="handlePreviousKeyframe"
          :disabled="!video.frames">
          <template #icon><left-outlined /></template>
        </a-button>
      </a-tooltip>
      <a-tooltip>
        <template #title>跳到最近的关键帧</template>
        <a-button
          @click="handleNearestKeyframe"
          :disabled="!video.frames">
          <template #icon><aim-outlined /></template>
        </a-button>
      </a-tooltip>
      <a-tooltip placement="topRight">
        <template #title>下一个关键帧 (&gt)</template>
        <a-button
          @click="handleNextKeyframe"
          :disabled="!video.frames">
          <template #icon><right-outlined /></template>
        </a-button>
      </a-tooltip>
    </div>
  </div>
</template>

<style>
.video-action .keyframe-panel {
  display: flex;
  gap: 1.5em;
  padding-top: 50px;
  margin-bottom: 24px;
}

.video-action .keyframe-panel .icon-stop {
  width: .75em;
  height: .75em;
  background: #000;
}

.video-action .keyframe-panel .btn-group {
  display: flex;
  gap: .35em;
}

.video-action .keyframe-panel .ant-slider { margin-inline: 0; }
.video-action .keyframe-panel .ant-slider > .ant-slider-rail { background-color: #fff; }
</style>